﻿#include <d3d9.h>
#include <d3dx9.h>
#include <time.h>
#include <stdio.h>
#include "GameManager.h"

HWND hwnd;
HINSTANCE hInst;
CGameManager * _game;

bool initWindows(HINSTANCE hInst);
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd )
{
	if(!initWindows(hInstance))
		return false;
	//Khai báo đôi tượng GameManager
	_game=new CGameManager();

	//initialize the game
	if(!_game->Init(hInstance,hwnd))
	{
		MessageBox(hwnd, "Error initializing the Init_Game", "Error", MB_OK);
		return false;
	}

	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	int done=0;

	DWORD frame_start = GetTickCount();
	DWORD tick_per_frame = 1000 / FRAME_RATE;
	//Main message loop
	while (!done)
	{
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			//look for quit message
			if(msg.message==WM_QUIT)
				done=1;
			//decode and pass messages in to WndProc
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			//Game loop
			DWORD now = GetTickCount();

			//_game->Run(hwnd,tick_per_frame);
			if (now - frame_start >= tick_per_frame) 
			{
				_game->Run(hwnd,tick_per_frame);
				frame_start = now;
			}
			else
				Sleep(1);
		}
	}
	return (int)msg.wParam;
}
bool initWindows(HINSTANCE hInst)
{
	//create the window class structure
	WNDCLASSEX wcex;
	//fill the struct with info
	wcex.cbClsExtra=0;
	wcex.cbSize=sizeof(WNDCLASSEX);
	wcex.cbWndExtra=0;
	wcex.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
	wcex.hCursor=LoadCursor(NULL,IDC_ARROW);
	wcex.hIcon=0;
	wcex.hIconSm=0;
	wcex.hInstance=hInst;
	wcex.lpfnWndProc=(WNDPROC)WndProc;
	wcex.lpszClassName=APP_CLASS;
	wcex.lpszMenuName=NULL;
	wcex.style=CS_HREDRAW|CS_VREDRAW;

	//set up the win dow with the class info
	RegisterClassEx(&wcex);

	//create a new window
	hwnd =CreateWindow(	APP_CLASS,
		APP_TITILE,
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		WINDOW_WIDTH,
		WINDOW_HEIGHT,
		NULL,
		NULL,
		hInst,
		NULL);
	if(!hwnd)
		return false;
	//display the window
	ShowWindow(hwnd,SW_SHOW);
	UpdateWindow(hwnd);
	return true;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}
	return DefWindowProc(hwnd,message,wParam,lParam);
}